package com.zy.mc_module.base;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Process;

import androidx.multidex.MultiDex;

import android.util.Log;
import android.widget.ImageView;

import com.danikula.videocache.HttpProxyCacheServer;
import com.fn.sdk.FnAdSDK;
import com.fn.sdk.config.FnConfig;
import com.google.gson.JsonElement;
import com.kingja.loadsir.core.LoadSir;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.DefaultRefreshFooterCreator;
import com.scwang.smartrefresh.layout.api.DefaultRefreshHeaderCreator;
import com.scwang.smartrefresh.layout.api.RefreshFooter;
import com.scwang.smartrefresh.layout.api.RefreshHeader;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.zy.mc_module.R;
import com.zy.mc_module.common.Config;
import com.zy.mc_module.utils.AppTools;
import com.zy.mc_module.utils.Logs;
import com.zy.mc_module.utils.SPUtil;
import com.zy.mc_module.utils.SystemUtil;
import com.zy.mc_module.utils.loadsir.EmptyCallback;
import com.zy.mc_module.utils.loadsir.ErrorCallback;
import com.zy.mc_module.utils.loadsir.LoadingCallback;
import com.zy.mc_module.view.MyBallPulseFooter;

import org.json.JSONObject;

import java.util.LinkedList;
import java.util.List;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * Created on 18/10/20
 * Application   开发版本
 */
public class App extends Application {
    private String TAG = "App-Lifecycle";
    private static App application;
    private static Context appContext;
    //全局
    private List<Activity> activitys;
    //临时
    private List<Activity> tmp_activitys;
    private Activity currentActivity;
    private static Handler sHandler = null;

    public static Activity getActivity() {
        return getInstance().currentActivity;
    }

    //声明一个监听Activity们生命周期的接口
    private ActivityLifecycleCallbacks activityLifecycleCallbacks = new ActivityLifecycleCallbacks() {
        /**
         * application下的每个Activity声明周期改变时，都会触发以下的函数。
         */
        @Override
        public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
            //如何区别参数中activity代表你写的哪个activity。
            Log.d(TAG, activity.getClass().getSimpleName() + " Created");
            currentActivity = activity;
        }

        @Override
        public void onActivityStarted(Activity activity) {
            Log.d(TAG, activity.getClass().getSimpleName() + " onActivityStarted.");
        }

        @Override
        public void onActivityResumed(Activity activity) {
            Log.d(TAG, activity.getClass().getSimpleName() + " onActivityResumed.");
        }

        @Override
        public void onActivityPaused(Activity activity) {
            Log.d(TAG, activity.getClass().getSimpleName() + " onActivityPaused.");
        }

        @Override
        public void onActivityStopped(Activity activity) {
            Log.d(TAG, activity.getClass().getSimpleName() + " onActivityStopped.");
        }

        @Override
        public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
        }

        @Override
        public void onActivityDestroyed(Activity activity) {
        }
    };

    public static Handler getHandler() {
        return sHandler;
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(base);
    }

    public void onCreate() {
        super.onCreate();

        /**
         * 初始化sdk
         */
        FnConfig config = new FnConfig.Builder().appId(Config.appId).test(true).debug(true).build();
        FnAdSDK.initFnSDK(this, config);


        application = this;
        appContext = getApplicationContext();
        sHandler = new Handler();
        //----
        activitys = new LinkedList<>();
        tmp_activitys = new LinkedList<>();
        application.registerActivityLifecycleCallbacks(activityLifecycleCallbacks);
        initThirdService();
    }

    private void initThirdService() {
        //内存泄漏分析
        //LeakCanary.install(this);
        //初始化融云
        //initRong();
        //注册LoadSir
        registerLoadSir();

        new Thread() {
            public void run() {
                super.run();
                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
                try {
                    SPUtil.init(application);
                    changeUrl();//正式/测试环境的判断
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    //SmartRefreshLayout
    //static 代码段可以防止内存泄露
    static {
        //设置全局的Header构建器
        SmartRefreshLayout.setDefaultRefreshHeaderCreator(new DefaultRefreshHeaderCreator() {
            @Override
            public RefreshHeader createRefreshHeader(Context context, RefreshLayout layout) {
                layout.setPrimaryColorsId(R.color.transparent);//全局设置主题颜色
                //指定为经典Header，默认是 贝塞尔雷达Header
                return new MaterialHeader(context)
                        .setColorSchemeColors(context.getResources().getColor(R.color.colorPrimary));//.setTimeFormat(new DynamicTimeFormat("更新于 %s"));
            }
        });
        //设置全局的Footer构建器
        SmartRefreshLayout.setDefaultRefreshFooterCreator(new DefaultRefreshFooterCreator() {
            @Override
            public RefreshFooter createRefreshFooter(Context context, RefreshLayout layout) {
                layout.setPrimaryColorsId(R.color.transparent);
                layout.setEnableOverScrollDrag(true);//是否启用越界拖动（仿苹果效果）
                //指定为经典Footer，默认是 BallPulseFooter
                return new MyBallPulseFooter(context)
                        .setNormalColor(context.getResources().getColor(R.color.colorPrimary))
                        .setAnimatingColor(context.getResources().getColor(R.color.colorPrimary));
            }
        });
    }

    private HttpProxyCacheServer proxy;

    public static HttpProxyCacheServer getProxy(Context context) {
        App app = (App) context.getApplicationContext();
        return app.proxy == null ? (app.proxy = app.newProxy()) : app.proxy;
    }

    private HttpProxyCacheServer newProxy() {
        return new HttpProxyCacheServer(this);
    }


    /***
     * 初始化LoadSir
     * 加载反馈页管理框架
     */
    private void registerLoadSir() {
        //设置错误页,空数据页,加载页,超时页-----默认页
        LoadSir.beginBuilder()
                .addCallback(new LoadingCallback())
                .addCallback(new ErrorCallback())
                .addCallback(new EmptyCallback())
                .commit();
    }

    /***
     * APP请求环境判断
     */
    private void changeUrl() {
        //默认正式环境
        AppTools.Base_Url = AppTools.APP_URL_ONLINE;//请求url
        AppTools.Base_Card_Url = AppTools.APP_CARD_URL;
        AppTools.share_Url = AppTools.APP_SHARE_URL_ONLINE;//正式环境分享url
        if ("swy".equals(SystemUtil.getChannel(appContext)) || SystemUtil.isDebugMode(this)) {
            //swy渠道 默认测试环境
            int isTest = SPUtil.getInt(AppTools.APP_URL_CHANGE, AppTools.APP_URL_TYPE_TEST);
            switch (isTest) {
                // 线上
                default:
                case AppTools.APP_URL_TYPE_ONLINE: {
                    AppTools.Base_Url = AppTools.APP_URL_ONLINE;//请求url
                    AppTools.Base_Card_Url = AppTools.APP_CARD_TEST_URL;
                    AppTools.share_Url = AppTools.APP_SHARE_URL_ONLINE;//线上环境分享url
                    break;
                }
                //预发
                case AppTools.APP_URL_TYPE_PRETEST: {
                    AppTools.Base_Url = AppTools.APP_URL_PRETEST;//请求url
                    AppTools.Base_Card_Url = AppTools.APP_CARD_URL;
                    AppTools.share_Url = AppTools.APP_SHARE_URL_PRETEST;//预发环境分享url
                    break;
                }
                //测试
                case AppTools.APP_URL_TYPE_TEST: {
                    AppTools.Base_Url = AppTools.APP_URL_TEST;//请求url
                    AppTools.Base_Card_Url = AppTools.APP_CARD_TEST_URL;
                    AppTools.share_Url = AppTools.APP_SHARE_URL_TEST;//测试环境分享url
                    break;
                }
                //开发
                case AppTools.APP_URL_TYPE_DEV: {
                    AppTools.Base_Url = AppTools.APP_URL_DEV;//请求url
                    AppTools.Base_Card_Url = AppTools.APP_CARD_TEST_URL;
                    AppTools.share_Url = AppTools.APP_SHARE_URL_DEV;//开发环境分享url
                    break;
                }
                case AppTools.APP_URL_TYPE_AUTO: {
                    AppTools.Base_Url = SPUtil.getString("auto_url", AppTools.APP_URL_ONLINE);//请求url
                    AppTools.Base_Card_Url = AppTools.APP_CARD_TEST_URL;
                    AppTools.share_Url = AppTools.Base_Url.replace("api", "h5");//开发环境分享url
                    break;
                }
            }
        }
    }

    public static App getInstance() {
        return application;
    }

    public static Context getAppContext() {
        return appContext;
    }

    /***
     * 添加Activity
     */
    public void addActivity(Activity activity) {
        if (!activitys.contains(activity)) {
            activitys.add(activity);
        }
    }

    /***
     * 添加临时Activity
     */
    public void addTmpActivity(Activity activity) {
        if (!tmp_activitys.contains(activity)) {
            tmp_activitys.add(activity);
        }
    }

    /***
     * 移出Activity
     */
    public void removeActivity(Activity activity) {
        if (activitys.contains(activity)) {
            activitys.remove(activity);
        }
    }

    /***
     * 移出临时Activity
     */
    public void removeTmpActivity(Activity activity) {
        if (tmp_activitys.contains(activity)) {
            tmp_activitys.remove(activity);
        }
    }

    /***
     * 关闭临时添加的Activity
     */
    public void finishTmpActivity() {
        for (Activity activity : tmp_activitys) {
            if (null != activity) {
                activity.finish();
            }
        }
        tmp_activitys.clear();
    }

    /**
     * 根据class获取activity
     */
    public Activity getActivity(Class cls) {
        Activity baseActivity = null;
        for (Activity activity : activitys) {
            if (activity.getClass().equals(cls)) {
                baseActivity = activity;
            }
        }
        return baseActivity;
    }


    /**
     * 结束指定类名的Activity
     */
    public void finishActivity(Class<?> cls) {
        Activity factivity = null;
        for (Activity activity : activitys) {
            if (activity.getClass().equals(cls)) {
                factivity = activity;
            }
        }
        finishActivity(factivity);
    }

    /**
     * 结束指定的Activity
     */
    public void finishActivity(Activity activity) {
        if (activity != null) {
            if (!activity.isFinishing()) {
                activity.finish();
            }
        }
    }

    /***
     * 关闭所有Activity并退出程序
     */
    public void finishActivity() {
        for (Activity activity : activitys) {
            if (null != activity) {
                Logs.Log_e(TAG, "activity   " + activity.toString());
                activity.finish();
            }
        }
        activitys.clear();
    }
}
